package com.yunji.base.business.common;

import com.yunji.base.bo.BelongSelectQueryBO;
import com.yunji.base.bo.ManagerUpdateBO;
import com.yunji.base.consumer.BaseDataConsumer;
import com.yunji.base.cache.BaseCache;
import com.yunji.base.domain.*;
import com.yunji.base.dto.AgentDTO;
import com.yunji.base.dto.SiteDTO;
import com.yunji.base.engine.generate.BaseDataCodeGenerate;
import com.yunji.base.enums.AgentMode;
import com.yunji.base.enums.AuditStatus;
import com.yunji.base.enums.ScaleTypes;
import com.yunji.base.enums.SwitchStatus;
import com.yunji.base.service.*;
import com.yunji.common.constant.LogicCode;
import com.yunji.common.constant.PrefixConstant;
import com.yunji.common.enums.business.AuditTypes;
import com.yunji.common.enums.common.ErrorEnum;
import com.yunji.common.enums.common.UserType;
import com.yunji.common.model.cache.ProductCacheDTO;
import com.yunji.common.model.domain.SiteDO;
import com.yunji.common.model.domain.SysUserDO;
import com.yunji.common.model.dto.LoginInfo;
import com.yunji.common.utils.ConvertDataUtil;
import com.yunji.common.utils.DecimalUtils;
import com.yunji.common.utils.SecurityUtils;
import com.yunji.common.utils.TimeUtils;
import com.yunji.common.utils.bean.BeanUtils;
import com.yunji.product.bo.ProductAgentListQueryBO;
import com.yunji.product.cache.ProductCache;
import com.yunji.product.domain.ProductAgentDO;
import com.yunji.system.context.SystemContext;
import com.yunji.system.service.ISysRoleService;
import com.yunji.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

import static com.yunji.common.constant.OSCode.*;

/**
 * @author : peter-zhu
 * @date : 2025/1/8 10:25
 * @description : 网点和网点审核公用类，可以拆分为：数据生成， 数据校验，规则引擎
 **/
@Service
@Slf4j
public class SiteAuditCommonBusiness {

    @Resource
    private SiteService siteService;
    @Resource
    private SiteAuditService siteAuditService;
    @Resource
    private AgentService agentService;
    @Resource
    private ISysRoleService roleService;
    @Resource
    private ISysUserService userService;
    @Resource
    private BelongService belongService;
    @Resource
    private ManagerService managerService;
    @Resource
    private AgentSiteService agentSiteService;
    @Resource
    private ManagerSiteService managerSiteService;
    @Resource
    private BaseDataConsumer baseDataConsumer;
    @Resource
    SiteScaleService siteScaleService;

    public static final String NOT_FIND_AGENT = "未找到代理信息";
    public static final String NOT_FIND_SITE = "未找到网点信息";
    public static final String NOT_FIND_MANAGER = "未找到网点用户信息";
    public static final String CUSTOM_PRICE_FAILURE = "授权网点定价失败";
    public static final String PARAM_USER = "user";
    public static final String PARAM_SITE = "site";
    public static final String PARAM_BELONG = "belong";
    public static final String PARAM_BELONG_ID = "parentBelongId";

    public Long handleCreateSite(SiteDTO dto) {
        boolean exemption = checkSiteScale(dto);
        log.info("【新增网点】审核豁免:{}[true:是;false:否]", exemption);
        if (!exemption) {
            return handleSiteAudit(dto, AuditStatus.WAIT.getCode(), AuditTypes.ACCOUNT.getCode());
        } else {
            Long auditId = handleSiteAudit(dto, AuditStatus.ACCEPT.getCode(), AuditTypes.ACCOUNT.getCode());
            dto.setAuditId(auditId);
            return handleAgentSupport(dto);
        }
    }

    public void handleUpdateSite(SiteDTO dto) {
        // 校验是否需要走审核
        boolean updateStatus = checkUpdateSiteScale(dto);

        Integer agentMode = dto.getCooperateWay();
        // 是否修改了分润
        if (updateStatus && AgentMode.SELF_SUPPORT.getCode().equals(agentMode)) {
            // 自营并且修改了分润方式则需要走审核
            // 校验是否免审
            if (!checkSiteScale(dto)) {
                handleSiteAudit(dto, AuditStatus.WAIT.getCode(), AuditTypes.SCALE.getCode());
            } else {
                Long auditId = handleSiteAudit(dto, AuditStatus.ACCEPT.getCode(), AuditTypes.SCALE.getCode());
                dto.setAuditId(auditId);
                updateCooperateWay(dto);
            }
        } else {
            // 没有修改分润
            updateCooperateWay(dto);
        }
    }

    public void handleUpdateAuditSite(SiteDTO dto) {
        // 自营并且修改了分润方式则需要走审核
        // 校验是否免审
        if (!checkSiteScale(dto)) {
            handleSiteAudit(dto, AuditStatus.WAIT.getCode(), AuditTypes.SCALE.getCode());
        } else {
            Long auditId = handleSiteAudit(dto, AuditStatus.ACCEPT.getCode(), AuditTypes.SCALE.getCode());
            dto.setAuditId(auditId);
            updateCooperateWay(dto);
        }
    }

    public Long handleSiteAudit(SiteDTO dto, Integer auditStatus, Integer auditType) {
        // 校验网点审核手机号是否唯一
        Assert.isTrue(!siteAuditService.checkUniqueAudit(dto.getSiteTel()), ErrorEnum.CHECKED_611005.getText());

        Long belongId = dto.get(PARAM_BELONG_ID);
        log.info("【新增网点】代理所属ID:{}", belongId);

        SiteAuditDO siteAudit = new SiteAuditDO();
        BeanUtils.clone(dto, siteAudit);
        siteAudit.setAuditType(auditType);
        siteAudit.setAuditStatus(auditStatus);
        siteAudit.setBelongId(belongId);
        siteAudit.setBelongName(BaseCache.getBelongName(belongId));
        siteAudit.setAgentName(BaseCache.getAgentName(siteAudit.getAgentId()));
        if (Objects.equals(AuditStatus.ACCEPT.getCode(), auditStatus)) {
            siteAudit.setAuditBelongId(1L);
            siteAudit.setAuditBelongName("系统");
            siteAudit.setAuditTime(TimeUtils.getNowDate());
        }
        if (BeanUtils.isNotNull(dto.getId())) siteAudit.setSiteId(dto.getId());
        siteAudit.setAuditCode(BaseDataCodeGenerate.generateSiteAuditCode(PrefixConstant.SITE_AUDIT_CODE_PREFIX));
        Assert.isTrue(siteAuditService.save(siteAudit), "新增失败");

        // 添加按合同分润比例信息
        List<SiteScaleDO> siteScaleList = dto.getSiteScaleList();
        if (BeanUtils.equals(dto.getScaleType(), ScaleTypes.CONTRACT.getCode())) {
            for (SiteScaleDO scaleDO : siteScaleList) {
                scaleDO.setId(null);
                scaleDO.setAuditId(siteAudit.getAuditId());
            }
            siteScaleService.saveBatch(siteScaleList);
        }
        return siteAudit.getAuditId();
    }


    /**
     * @param dto 上送网点信息
     * @Title checkSite
     * @Desc 检查代理商, 经理信息
     * @Date 2024-05-31 16:57:54.426
     */
    public void checkSite(SiteDTO dto) {
        String phone = dto.getSiteTel();
        String contacts = dto.getSiteContacts();
        log.info("【网点信息】网点联系人:{},联系人电话:{}", contacts, phone);
        Assert.isTrue(BeanUtils.isNotNull(phone), "未找到联系人电话");
        Assert.isTrue(BeanUtils.isNotNull(contacts), "未找到联系人信息");

        LoginInfo user = SystemContext.getUser();
        String userType = user.getUserType();

        if (!Objects.equals(userType, UserType.PLATE.getCode())) {
            Long belongId = user.getBelongId();
            log.info("【网点信息】当前用户所属ID:{}", belongId);
            BelongDO belong = belongService.getById(belongId);
            log.info("【网点信息】当前用户所属:{}", belong);
            Assert.isTrue(BeanUtils.isNotNull(belong), "当前用户非法操作");
            dto.setAgentId(belong.getAgentId());
        }
        Long agentId = dto.getAgentId();
        log.info("【网点信息】代理ID:{}", agentId);
        Assert.isTrue(BeanUtils.isNotNull(agentId), NOT_FIND_AGENT);
        AgentDTO agent = agentService.select(agentId);
        Assert.isTrue(BeanUtils.isNotNull(agent), NOT_FIND_AGENT);
        dto.setCooperateWay(agent.getCooperateWay());
        dto.set(PARAM_BELONG_ID, agent.getBelongId());
    }


//    public void checkPhone(String phone) {
//        String phone = dto.getSiteTel();
//        SysUserDO checkUser = new SysUserDO();
//        checkUser.setUserName(phone);
//        Assert.isTrue(userService.checkUserNameUnique(checkUser), ErrorEnum.BUSINESS_121001.getText());
//    }

    /**
     * 校验修改自营网点分润
     */
    public boolean checkUpdateSiteScale(SiteDTO dto) {
        BigDecimal scale = dto.getScale();
        Integer scaleType = dto.getScaleType();

        BelongDO siteBelong = belongService.select(BelongSelectQueryBO.builder().belongType(UserType.SITE.getCode()).siteId(dto.getId()).build());
        Assert.isTrue(BeanUtils.isNotNull(siteBelong), ErrorEnum.BUSINESS_612002.getText());

        Integer oldScaleType = siteBelong.getScaleType();
        BigDecimal oldScale = siteBelong.getScaleRatio();

        // 按年限分润
        if (BeanUtils.equals(scaleType, ScaleTypes.CONTRACT.getCode())) {
            List<SiteScaleDO> scaleDOList = siteScaleService.listBySiteId(dto.getId());
            if (scaleDOList != null && !scaleDOList.isEmpty()) {
                Map<Integer, SiteScaleDO> map = ConvertDataUtil.getDataMap(() -> scaleDOList, SiteScaleDO::getScaleYear);
                for (SiteScaleDO siteScaleDO : dto.getSiteScaleList()) {
                    SiteScaleDO checkScale = map.get(siteScaleDO.getScaleYear());
                    if (!DecimalUtils.compare(siteScaleDO.getScaleRatio(), checkScale.getScaleRatio())) {
                        return true;
                    }
                }
            }
        }

        return !scaleType.equals(oldScaleType) || !DecimalUtils.compare(scale, oldScale);
    }

    /**
     * @param dto 网点信息
     * @Title checkSiteScale
     * @Desc 校验自营网点分润
     * @Date 2024-09-12 17:20:51.877
     * @Return boolean 校验结果
     */
    public boolean checkSiteScale(SiteDTO dto) {

        Integer scaleType = dto.getScaleType();
        String scaleText = ScaleTypes.get(scaleType);
        log.info("【网点信息】网点分润方式={}:{}", scaleType, scaleText);
        if (!BeanUtils.equals(scaleType, ScaleTypes.RATIO.getCode(), ScaleTypes.CONTRACT.getCode())) {
            return true;
        }

        boolean isAudit = Boolean.TRUE;

        // 按比例分润
        if (BeanUtils.equals(scaleType, ScaleTypes.RATIO.getCode())) {
            isAudit = handleScale(dto.getScale());
        }

        // 按年限分润
        if (BeanUtils.equals(scaleType, ScaleTypes.CONTRACT.getCode())) {
            List<SiteScaleDO> scaleList = dto.getSiteScaleList();
            for (SiteScaleDO scaleDO : scaleList) {
                isAudit = handleScale(scaleDO.getScaleRatio());
                if (!isAudit) break;
            }
        }

        return isAudit;
    }

    /**
     * @Title handleScale
     * @Desc 审核网点分润
     * @Date 2024-11-08 11:14:46.685
     * @Return boolean
     */
    public boolean handleScale(BigDecimal scaleRatio) {

        String maxRatio = baseDataConsumer.selectConfigByKey(MAX_PRICE);
        log.info("【网点信息】自营最大分润比例:{}", maxRatio);
        Assert.isTrue(BeanUtils.isNotNull(maxRatio), "未找到可配置网点分润最高值");

        BigDecimal maxPrice = BeanUtils.getDecimal(maxRatio, BigDecimal.ZERO);
        log.info("【网点信息】自营最大分润比例:{}", maxPrice);
        Assert.isTrue(!DecimalUtils.more(scaleRatio, maxPrice), "网点分润超出限制");

        String minExemptRatio = baseDataConsumer.selectConfigByKey(MIN_SCALE);
        String maxExemptRatio = baseDataConsumer.selectConfigByKey(MAX_SCALE);
        log.info("【网点信息】自营豁免范围最小值:{}, 最大值:{}", minExemptRatio, maxExemptRatio);
        Assert.isTrue(BeanUtils.isNotNull(minExemptRatio), "未找到免审范围最小值");
        BigDecimal minScale = BeanUtils.getDecimal(minExemptRatio, BigDecimal.ZERO);

        Assert.isTrue(BeanUtils.isNotNull(maxExemptRatio), "未找到免审范围最大值");
        BigDecimal maxScale = BeanUtils.getDecimal(maxExemptRatio, BigDecimal.ZERO);
        log.info("【网点信息】自营豁免范围最小值:{}, 最大值:{}", minScale, maxScale);

        return !DecimalUtils.less(scaleRatio, minScale) && !DecimalUtils.more(scaleRatio, maxScale);
    }

    /**
     * @param dto 网点信息
     * @Title createBelong
     * @Desc 创建属组信息
     * @Date 2024-09-12 09:58:33.457
     * @Return Belong 属组信息
     */
    public void createBelong(SiteDTO dto) {
        Long agentId = dto.getAgentId();
        log.info("【网点信息】代理商ID:{}", agentId);

        AgentDTO agent = agentService.getById(agentId);
        log.info("【网点信息】代理信息:{}", agent);
        Assert.isTrue(BeanUtils.isNotNull(agent), "未找到代理商信息");

        BelongDO belong = new BelongDO();
        belong.setBelongName(dto.getSiteName());
        belong.setBelongType(UserType.SITE.getCode());

        Integer customPrice = dto.getCustomPrice();
        log.info("【网点信息】自定义价格:{}", customPrice);
        belong.setCustomPrice(customPrice);

        Integer scaleType = dto.getScaleType();
        String scaleText = ScaleTypes.get(scaleType);
        log.info("【网点信息】分润方式={}:{}", scaleType, scaleText);
        belong.setScaleType(scaleType);

        Integer model = agent.getCooperateWay();
        String text = AgentMode.get(model);
        BigDecimal scaleRatio = BeanUtils.getDecimal(dto.getScale());
        log.info("【网点信息】代理模式={}:{},网点分润比例:{},", model, text, scaleRatio);


        // 如果是按年限分润得看时间
        if (BeanUtils.equals(dto.getScaleType(), ScaleTypes.CONTRACT.getCode())) {
            Date startDate = dto.getSiteScaleDates();
            Date nowDate = TimeUtils.getNowDate();
            int i = TimeUtils.differentByMillisecond(startDate, nowDate, Calendar.YEAR) + 1;

            List<SiteScaleDO> siteScaleList = dto.getSiteScaleList();
            if (startDate.after(nowDate)) {
                scaleRatio = dto.getSiteScaleList().get(0).getScaleRatio();
            } else {
                for (SiteScaleDO scaleDO : siteScaleList) {
                    if (scaleDO.getScaleYear() == i) {
                        scaleRatio = scaleDO.getScaleRatio();
                        break;
                    }
                    if (scaleDO.getScaleYear() == 4) {
                        scaleRatio = scaleDO.getScaleRatio();
                    }
                }
            }
        }

        // 自营代理 分润不能超过百分百 合作代理分润不能超过代理
        Long belongId = agent.getBelongId();
        log.info("【网点信息】代理商所属ID:{}", belongId);
        BelongDO agentBelong = BaseCache.getBelong(belongId);
        Integer agentMode = agentBelong.getAgentMode();
        BigDecimal agentRatio = agentBelong.getScaleRatio();
        if (AgentMode.SELF_SUPPORT.getCode().equals(agentMode)) {
            Assert.isTrue(!DecimalUtils.more(agentRatio.add(scaleRatio), new BigDecimal("100")), ErrorEnum.BUSINESS_512009.getText());
        } else {
            Assert.isTrue(!DecimalUtils.more(scaleRatio, agentRatio), ErrorEnum.BUSINESS_512009.getText());
        }

        belong.setScaleRatio(scaleRatio);
        belong.setAgentId(agent.getId());
        belong.setParentId(belongId);
        Assert.isTrue(belongService.create(belong), "新增网点失败");
        dto.setScale(scaleRatio);
        dto.set(PARAM_BELONG, belong);
    }

    /**
     * @param dto 网点信息
     * @Title createUser
     * @Desc 创建用户信息
     * @Date 2024-09-12 10:11:09.710
     * @Return SysUser 用户信息
     */
    public void createUser(SiteDTO dto) {
        String phone = dto.getSiteTel();
        Long roleId = roleService.selectRoleByRoleCode(UserType.SITE.getCode());
        Assert.isTrue(BeanUtils.isNotNull(roleId), "站点授权失败");

        BelongDO belong = dto.get(PARAM_BELONG);
        Long belongId = belong.getBelongId();

        SysUserDO user = new SysUserDO();
        String password = phone.substring((phone.length() - 6));
        String encrypt = SecurityUtils.encryptPassword(password);
        user.setUserName(phone);
        user.setUserType(UserType.SITE.getCode());
        user.setNickName(dto.getSiteContacts());
        user.setPhonenumber(phone);
        user.setPassword(encrypt);
        user.setRoleIds(roleId);
        user.setBelongId(belongId);
        user.setMainAccount(LogicCode.YES);
        Assert.isTrue((userService.insertUser(user) > 0), "创建经理用户失败");
        dto.set(PARAM_USER, user);
    }

    /**
     * @param dto 网点信息
     * @Title updateCooperateWay
     * @Desc 修改自营代理网点信息
     * @Date 2024-09-12 19:37:32.878
     */
    public void updateCooperateWay(SiteDTO dto) {
        String phone = dto.getSiteTel();

        Long siteId = dto.getId();
        log.info("【网点信息】修改网点ID{}", siteId);
        Assert.isTrue(BeanUtils.isNotNull(siteId), NOT_FIND_SITE);

        SiteDO site = siteService.getById(siteId);
        log.info("【网点信息】网点信息:{}", site);
        Assert.isTrue(BeanUtils.isNotNull(site), NOT_FIND_SITE);
        dto.set(PARAM_SITE, site);

        ManagerSiteDO managerSite = managerSiteService.getBySiteId(siteId);
        Assert.isTrue(BeanUtils.isNotNull(managerSite), NOT_FIND_MANAGER);

        Long userId = managerSite.getManagerId();
        log.info("【网点信息】网点用户ID{},修改手机号{}", userId, phone);

        SysUserDO checkUser = new SysUserDO();
        checkUser.setUserId(userId);
        checkUser.setUserName(phone);
        Assert.isTrue(userService.checkUserNameUnique(checkUser), "网点用户名称已存在");


        Integer scaleType = dto.getScaleType();
        String scaleText = ScaleTypes.get(scaleType);
        BigDecimal scaleRatio = BeanUtils.getDecimal(dto.getScale());
        log.info("【网点信息】分润类型={}:{},分润比例:{}", scaleType, scaleText, scaleRatio);

        Integer customPrice = dto.getCustomPrice();
        String text = SwitchStatus.get(customPrice);
        log.info("【网点信息】自定义价格={}:{}", customPrice, text);

        // 如果是按年分润  先删除 后新增
        if (BeanUtils.equals(ScaleTypes.CONTRACT.getCode(), scaleType)) {
            siteScaleService.deleteBySiteId(siteId);
            Long auditId = dto.getAuditId();
            if (BeanUtils.isNotNull(auditId)) {
                siteScaleService.deleteByAuditId(auditId);
            }

            List<SiteScaleDO> scaleList = dto.getSiteScaleList();
            for (SiteScaleDO scaleDO : scaleList) {
                scaleDO.setSiteId(siteId);
                scaleDO.setId(null);
                scaleDO.setAuditId(dto.getAuditId());
            }

            siteScaleService.saveBatch(scaleList);

            Date startDate = dto.getSiteScaleDates();
            Date nowDate = TimeUtils.getNowDate();
            int i = TimeUtils.differentByMillisecond(startDate, nowDate, Calendar.YEAR) + 1;

            List<SiteScaleDO> siteScaleList = dto.getSiteScaleList();
            if (startDate.after(nowDate)) {
                scaleRatio = siteScaleList.get(0).getScaleRatio();
            } else {
                for (SiteScaleDO scaleDO : siteScaleList) {
                    if (scaleDO.getScaleYear() == i) {
                        scaleRatio = scaleDO.getScaleRatio();
                        break;
                    }
                    if (scaleDO.getScaleYear() == 4) {
                        scaleRatio = scaleDO.getScaleRatio();
                    }
                }
            }
        }

        ManagerUpdateBO manager = new ManagerUpdateBO(userId, scaleRatio, scaleType, customPrice);

        Assert.isTrue(managerService.updateByManager(manager), CUSTOM_PRICE_FAILURE);

        AgentDTO agent = agentService.getById(dto.getAgentId());
        Long agentBelongId = agent.getBelongId();
        BelongDO agentBelong = BaseCache.getBelong(agentBelongId);
        Integer agentMode = agentBelong.getAgentMode();
        BigDecimal agentRatio = agentBelong.getScaleRatio();
        if (AgentMode.SELF_SUPPORT.getCode().equals(agentMode)) {
            Assert.isTrue(!DecimalUtils.more(agentRatio.add(scaleRatio), new BigDecimal("100")), ErrorEnum.BUSINESS_512009.getText());
        } else {
            Assert.isTrue(!DecimalUtils.more(scaleRatio, agentRatio), ErrorEnum.BUSINESS_512009.getText());
        }

        Long belongId = site.getBelongId();
        BelongDO belong = new BelongDO();
        belong.setBelongId(belongId);
        belong.setBelongName(dto.getSiteName());
        belong.setScaleType(scaleType);
        belong.setScaleRatio(scaleRatio);
        belong.setCustomPrice(customPrice);
        Assert.isTrue(belongService.update(belong), CUSTOM_PRICE_FAILURE);

        Long role = roleService.selectRoleByRoleCode(UserType.SITE.getCode());
        Assert.isTrue(BeanUtils.isNotNull(role), "修改网点失败");

        SysUserDO user = new SysUserDO();
        user.setUserId(userId);
        user.setUserName(phone);
        user.setRoleIds(role);
        user.setNickName(dto.getSiteContacts());
        user.setPassword(SecurityUtils.encryptPassword(phone.substring(phone.length() - 6)));
        user.setPhonenumber(phone);
        userService.updateUser(user);

        SiteDO update = new SiteDO();
        BeanUtils.clone(dto, update);
        update.setBelongId(null);
        update.setId(dto.getId());
        Assert.isTrue(siteService.update(update), "修改网点信息失败");
    }

    /**
     * @param agentList 代理商商品信息
     * @param belongId  网点所属ID
     * @param siteId    网点ID
     * @Title createSiteProduct
     * @Desc 创建网点商品
     * @Date 2024-09-13 19:54:36.568
     */
    public void createSiteProduct(List<ProductAgentDO> agentList, Long belongId, Long siteId) {
        if (BeanUtils.isNull(agentList)) {
            return;
        }
        List<ProductAgentDO> creates = new ArrayList<>();
        for (ProductAgentDO agent : agentList) {
            ProductAgentDO productAgent = new ProductAgentDO();

            BigDecimal agentPrice = agent.getAgentPrice();
            ProductCacheDTO product = ProductCache.getProduct(agent.getProductId());
            Assert.isTrue(BeanUtils.isNotNull(product), ErrorEnum.BUSINESS_512008.getText());
            BigDecimal price = DecimalUtils.compare(agentPrice) ? product.getDiscountPrice() : agentPrice;
            productAgent.setDiscountPrice(price);

            productAgent.setSiteId(siteId);
            productAgent.setBelongId(belongId);

            productAgent.setAgentId(agent.getAgentId());
            productAgent.setStatus(agent.getStatus());
            productAgent.setCostPrice(agent.getCostPrice());
            productAgent.setPrice(agent.getPrice());
            productAgent.setProductId(agent.getProductId());

            productAgent.setUserType(UserType.SITE.getCode());

            productAgent.setDelFlag(0);
            productAgent.setChangeStatus(0);
            productAgent.setId(null);
            creates.add(productAgent);
        }
        if (BeanUtils.isNull(creates)) {
            return;
        }

        for (ProductAgentDO pa : creates) {
            Assert.isTrue(baseDataConsumer.createProductAgent(pa), "新增失败");
        }
    }

    /**
     * @param dto 网点信息
     * @Title handleAgentSupport
     * @Desc 处理合作代理
     * @Date 2024-08-22 11:46:58.126
     */
    public Long handleAgentSupport(SiteDTO dto) {

        createBelong(dto);

        BelongDO belong = dto.get(PARAM_BELONG);

        Long belongId = belong.getBelongId();
        log.info("【网点信息】网点所属信息:{}", belongId);

        SiteDO site = new SiteDO();
        BeanUtils.clone(dto, site);
        site.setBelongId(belongId);
        Assert.isTrue(siteService.create(site), "创建网点失败");
        dto.set(PARAM_SITE, site);

        Long agentId = dto.getAgentId();
        Long siteId = site.getId();
        log.info("【网点信息】新增网点ID:{},所属代理ID:{}", siteId, agentId);
        dto.setId(siteId);

        // 添加按合同分润比例信息
        List<SiteScaleDO> siteScaleList = dto.getSiteScaleList();
        if (BeanUtils.equals(dto.getScaleType(), ScaleTypes.CONTRACT.getCode())) {
            if (BeanUtils.isNotNull(dto.getAuditId())) {
                siteScaleService.setSiteIdByAuditId(siteId, dto.getAuditId());
            } else {
                for (SiteScaleDO siteScaleDO : siteScaleList) {
                    siteScaleDO.setId(null);
                }
                siteScaleService.saveBatch(siteScaleList);
            }
        }

        ProductAgentListQueryBO productAgent = new ProductAgentListQueryBO();
        productAgent.setAgentId(agentId);
        productAgent.setUserType(UserType.AGENT.getCode());
        productAgent.setStatus(LogicCode.NO);
        List<ProductAgentDO> agentList = baseDataConsumer.searchProductAgent(productAgent);
        createSiteProduct(agentList, belongId, siteId);

        // 绑定代理网点信息
        AgentSiteDO agentSite = new AgentSiteDO();
        agentSite.setSiteId(siteId);
        agentSite.setAgentId(agentId);
        Assert.isTrue(agentSiteService.create(agentSite), "代理网点绑定失败");

        createUser(dto);
        SysUserDO user = dto.get(PARAM_USER);
        Long userId = user.getUserId();
        log.info("【网点信息】创建用户ID:{}", userId);

        BelongDO update = new BelongDO();
        update.setBelongId(belongId);
        update.setSiteId(siteId);
        update.setUserId(userId);
        Assert.isTrue(belongService.update(update), "创建网点失败");

        ManagerDO manager = new ManagerDO();
        BeanUtils.clone(dto, manager);
        manager.setManagerId(userId);
        Assert.isTrue(managerService.create(manager), "创建经理用户失败");

        ManagerSiteDO managerSite = new ManagerSiteDO();
        managerSite.setSiteId(dto.getId());
        managerSite.setManagerId(userId);
        Assert.isTrue(managerSiteService.create(managerSite), "代理网点绑定失败");

        return siteId;
    }
}
